package com.example.layoutincompose

import android.os.Bundle
import android.view.View
import android.view.View.SYSTEM_UI_FLAG_IMMERSIVE
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Face
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.focusModifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import coil.compose.rememberImagePainter
import coil.size.Scale
import com.example.layoutincompose.ui.theme.LayoutInComposeTheme
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            LayoutInComposeTheme {

                // A surface container using the 'background' color from the theme
//                Surface(color = MaterialTheme.colors.background) {
//                    Greeting("Android")
//                    PhotographerCard()
//                    SurfaceShow()
//                }


                // Scaffold 脚手架实例
//                LayoutInCompose()


//                ConstraintLayoutDemo1()  // 约束布局实例
//                LargeConstraintLayout()
//                DecoupledConstraintLayout()
//                ConstraintLayoutChainDemo()


                // 自定义 Layout Demo
//                CustomLayoutDemo()
//                MyOwnColumnDemo()

                // 自定义复杂 Layout Demo
//                val topics = listOf(
//                    "Arts & Crafts", "Beauty", "Books", "Business", "Comics", "Culinary",
//                    "Design", "Fashion", "Film", "History", "Maths", "Music", "People", "Philosophy",
//                    "Religion", "Social sciences", "Technology", "TV", "Writing"
//                )
//                Row(modifier = Modifier.horizontalScroll(rememberScrollState())){
//                    StaggeredGrid() {
//                        for (topic in topics) {
//                            Chip(modifier = Modifier.padding(8.dp),text = topic)
//                        }
//                    }
//                }


                // 自定义 Layout 实现固有特性测量
                MyColumn(modifier = Modifier.width(IntrinsicSize.Min)) {
                    Text(text = "watermelon")
                    Text("apple")
                    Divider(color = Color.Black, modifier = Modifier.height(2.dp).fillMaxWidth())
                    Text("orange")
                }

//                TwoTextsColumn(text1 = "sfasfwefawefwesfasfwefawefwe", text2 = "fwefw")
            }
        }
    }


    @Composable
    fun LayoutInCompose() {
        var selectedItem by remember { mutableStateOf(0) }
        val navItems = listOf("Songs", "Artists", "Playlists")

        Scaffold(
            topBar = {  // topBar 属性用于设置 AppBar
                TopAppBar(
                    title = {  // 可设置标题
                        Text(text = "LayoutInCompose")
                    },
                    actions = {  // 设置 AppBar 上的按钮 Button
                        IconButton(onClick = { /*TODO*/ }) {
                            // Icon 系统为我们提供了许多常见的 Icon
                            Icon(Icons.Filled.Favorite, contentDescription = null)
                        }
                    }
                )
            },
            bottomBar = {  // bottomBar 可用于设置 BottomNavigation
                BottomNavigation() {
                    navItems.forEachIndexed { index, item ->
                        BottomNavigationItem(
                            icon = { Icon(Icons.Filled.Face, contentDescription = null) },
                            label = { Text(item) },
                            selected = selectedItem == index,
                            onClick = { selectedItem = index }
                        )
                    }
                }
            }
        ) {
            BodyContent(
                modifier = Modifier
                    .padding(it)
                    .padding(10.dp)
            )
        }
    }


    @Composable
    fun BodyContent(modifier: Modifier) {
        Column(modifier = modifier) {
            Text(text = "Hi there!")
            Text(text = "Thanks for watching this",Modifier.padding(bottom = 10.dp))
//        SimpleList()
//        LazyList()
            ScrollingList()
        }
    }


    @Composable
    fun ScrollingList() {
        val listSize = 100
        // 使用 rememberLazyListState 保存滚动的位置
        val scrollState = rememberLazyListState()
        // 当滚动动效将要执行时，使用 rememberCoroutineScope 保存 范围
        val coroutineScope = rememberCoroutineScope()

        Column {
//        Row{
//            Button(onClick = {
//                coroutineScope.launch {
//                    // 0 是首个 Item 的索引位置
//                    scrollState.animateScrollToItem(0)
//                }
//            }) {
//                Text(text = "Scroll to the top")
//            }
//
//            Button(onClick = {
//                coroutineScope.launch {
//                    // listSize - 1 是 list 最后一个元素的索引位置
//                    scrollState.animateScrollToItem(listSize - 1)
//                }
//            }) {
//                Text(text = "Scroll to the end")
//            }
//        }

            LazyColumn(state = scrollState) {
                items(listSize) {
                    ImageListItem(index = it)
                    Divider(color = Color.Blue, thickness = 1.5.dp, startIndent = 60.dp)
                }
            }
        }

    }


    @Composable
    fun ImageListItem(index: Int) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(5.dp)  // 外边距
                .clip(RoundedCornerShape(6.dp)) // 圆角
                .clickable {
                    // 点击事件
                    Toast
                        .makeText(this@MainActivity, "$index 被点击了", Toast.LENGTH_SHORT)
                        .show()
                }
                .padding(5.dp),  // 内边距
            contentAlignment = Alignment.CenterEnd
        ) {
            Image(painter = painterResource(R.drawable.ic_item_bg),
                contentDescription = "item bg img",
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(5.dp)),
                contentScale = ContentScale.Crop,
                alpha = 0.3f)
            Row(verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
            ) {
                Surface(
                    modifier = Modifier.size(50.dp),  // 设置大小
                    shape = CircleShape,  // 设置形状
                    color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f)  // 设置色值
                ) {
                    // 加载网络图片逻辑
                    Image(
                        painter = rememberImagePainter(
                            data = "https://pic.ntimg.cn/20140810/3822951_180850680000_2.jpg"
                        ),
                        contentDescription = "dog img",
                        modifier = Modifier.size(50.dp),
                        contentScale = ContentScale.Crop  // 居中裁剪
                    )
                }

                Column(
                    modifier = Modifier
                        .padding(start = 8.dp)  // 单独设置 左边距
                        .align(Alignment.CenterVertically)  // 设置里面的子元素竖直方向上居中分布
                ) {
                    Text("Item #$index", fontWeight = FontWeight.Bold)
                    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
                        Text("${index}分钟前来过", style = MaterialTheme.typography.body2)
                    }
                }
            }
        }
    }
}


@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    LayoutInComposeTheme {
        Greeting("Jetpack")
    }
}

// compositionLocalOf 方法可以创建一个 CompositionLocal 实例
val ActiveUser = compositionLocalOf {
    // 设置默认值
    User("小明", "3分钟")
    // 如果无须默认值，也可设置错误信息
//    error("No active user found!")
}

@Composable
fun PhotographerCard() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp)
            .clip(RoundedCornerShape(6.dp))
            .clickable { }
            .padding(16.dp)
    ) {
        Surface(
            modifier = Modifier.size(50.dp),  // 设置大小
            shape = CircleShape,  // 设置形状
            color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f)  // 设置色值
        ) {
            // 加载网络图片逻辑
        }

        Column(
            modifier = Modifier
                .padding(start = 8.dp)
                .align(Alignment.CenterVertically)
        ) {
            val user = ActiveUser.current // 通过 current 方法取出当前值
            Text(user.name, fontWeight = FontWeight.Bold)
            CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
                Text(user.lastActiveTime, style = MaterialTheme.typography.body2)
            }

            /*// 通过 providers 中缀表达式可以重新对 CompositionLocal 实例赋值
            CompositionLocalProvider(ActiveUser provides User("小红", "5分钟前")) {
                val newUser = ActiveUser.current
                Text(newUser.name, fontWeight = FontWeight.Bold)
                CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
                    Text(newUser.lastActiveTime, style = MaterialTheme.typography.body2)
                }
            }*/
        }
    }

}

@Preview
@Composable
fun PhotographerCardPreview() {
    LayoutInComposeTheme {
        PhotographerCard()
    }
}

data class User(
    val name: String,
    val lastActiveTime: String
)


@Composable
fun SimpleList() {
    // 使用 rememberScrollState 保存滚动的位置信息
    val scrollState = rememberScrollState()
    // Modifier.verticalScroll 可添加竖直方向上的滚动属性
    // 使用 Column 的 Modifier.verticalScroll 方法确实可以创建一个可滑动的
    // List，但是这种方法在开始时就会将所有 item 全部加载，类似于 ScrollView
    Column(Modifier.verticalScroll(scrollState)) {
        repeat(100) {
//            ImageListItem(it)
//            Text(text = "Item #$it")
            Divider(color = Color.Blue, thickness = 1.5.dp, startIndent = 10.dp)
        }
    }
}

@Composable
fun LazyList() {
    val scrollState = rememberLazyListState()
    LazyColumn(state = scrollState) {
        items(100) {
//            Text(text = "LazyList Item #$it")
//            ImageListItem(index = it)
            Divider(color = Color.Blue, thickness = 1.5.dp, startIndent = 10.dp)
        }
    }
}




